package cn.tedu.myweb.controller;

import cn.tedu.myweb.exception.ServiceException;
import cn.tedu.myweb.model.Notify;
import cn.tedu.myweb.service.IFriendsService;
import cn.tedu.myweb.service.INotifyService;
import cn.tedu.myweb.vo.NotifyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("v1/notify")
@Slf4j
public class NotifyController {
    @Autowired
    INotifyService notifyService;

    @Autowired
    IFriendsService friendsService;

    @GetMapping("/my")
    public List<Notify> getNotifies(
            @AuthenticationPrincipal UserDetails user
            ){
        List<Notify> notifyList = notifyService.getNotifies(user.getUsername());
        return notifyList;
    }

    @PostMapping("")
    public String addNotify(NotifyVo notifyVo,
                          @AuthenticationPrincipal UserDetails user){
        log.debug("接收到的用户信息{}",notifyVo);

        try {
            notifyService.saveNotify(notifyVo,user.getUsername());
            return "OK";
        } catch (ServiceException e) {
            log.error("发送失败！");
            return e.getMessage();
        }

    }

    @GetMapping("/{friendname}")
    public String addFriend(
            @PathVariable String friendname,
            @AuthenticationPrincipal UserDetails userDetails){
        System.out.println("jj");
        log.debug("接收到用户信息:{}",friendname);
        friendsService.addRoom(userDetails.getUsername(),friendname);
        friendsService.addFriends(friendname,userDetails.getUsername());
        return "OK";
    }
}
